<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>体验websocket</title>
  <style>
    #contanier {
      width: 500px;
      height: 400px;
      border: 2px dashed #7575e7;
      overflow-y: auto;
    }
  </style>
</head>

<body>
  <div id="contanier"></div>
  <!-- 1  建立连接 (拨号) -->
  <!-- 2  发消息 接消息 -->
  <!-- 3  关闭连接 -->
  <input type="text" id="message" />
  <button id="btn1">建立连接</button>
  <button id="btn2">发送消息</button>
  <button id="btn3">关闭连接</button>

  <script>
    var dom = document.getElementById('contanier')
    var inputDom = document.getElementById('message')
    var btn1 = document.getElementById('btn1')
    var btn2 = document.getElementById('btn2')
    var btn3 = document.getElementById('btn3')

    var isOpen = false // 表示是否已经建立了拨号
    var ws // 别的方法 也需要使用ws

    btn1.onclick = function () {
      ws = new WebSocket('ws://121.40.165.18:8800')

      ws.onopen = function (event) {
        isOpen = true
        // 建立成功
        dom.innerHTML = dom.innerHTML + `<p>与服务器连接成功</p>`
      }

      ws.onmessage = function (event) {
        dom.innerHTML = dom.innerHTML + `<p style='color:blue'>服务器说：${event.data}</p>`
      }
      ws.onclose = function(){
        isOpen = false
        dom.innerHTML = dom.innerHTML +  `<p>与服务器连接关闭</p>`
      }
    }

    // 发消息接收消息
    btn2.onclick = function(){
      if(inputDom.value && isOpen){
        ws.send(inputDom.value)

        dom.innerHTML = dom.innerHTML + `<p style='color: red'>我说：${inputDom.value}</p>`
        inputDom.value = ''
      }
        
      // 关闭连接
      btn3.onclick = function(){
        ws.close()
      }
    }

  </script>
</body>

</html>